package com.taiji.dianthus.api.sms;

import com.alibaba.fastjson.JSONObject;
import com.taiji.dianthus.common.BasicController;
import com.taiji.dianthus.common.BusinessMessage;
import com.taiji.dianthus.domain.app.AppInfo;
import com.taiji.dianthus.domain.sms.SmsAccount;
import com.taiji.dianthus.domain.sms.SmsBackInfo;
import com.taiji.dianthus.domain.sms.SmsInfo;
import com.taiji.dianthus.domain.sms.SmsMoInfo;
import com.taiji.dianthus.domain.sms.api.SmsDomain;
import com.taiji.dianthus.service.api.SmsPublicUseService;
import com.taiji.dianthus.service.app.AppInfoService;
import com.taiji.dianthus.service.sms.SmsAccountService;
import com.taiji.dianthus.service.sms.SmsBackInfoService;
import com.taiji.dianthus.service.sms.SmsInfoService;
import com.taiji.dianthus.service.sms.SmsMoInfoService;
import com.taiji.dianthus.sms.HttpSendSmsService;
import com.taiji.dianthus.util.DStringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @ClassName SmsInfoController
 * @Description
 * @Author H.M
 * @Date 2020/7/15
 */
@Api(value = "短信api类")
@RestController
@RequestMapping(value = "/api/sms")
public class SmsInfoController extends BasicController {

    @Autowired
    private SmsPublicUseService publicUseService;
    @Autowired
    private SmsMoInfoService moInfoService;

    @Autowired
    private HttpSendSmsService httpSendSmsService;
    @Autowired
    private SmsBackInfoService smsBackInfoService;

    @Autowired
    private SmsAccountService accountService;

    @Autowired
    private SmsInfoService infoService;

    @Autowired
    private AppInfoService appInfoService;


    @RequestMapping(value = "/saveAndSend", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "发送短信并保存相关信息", notes = "发送短信并保存相关信息接口")
    @ApiImplicitParam(name = "form", value = "SmsInfo实体", required = true, dataType = "SmsInfo")
    public JSONObject sendMessage(HttpServletRequest request, @RequestBody SmsDomain domain) {
        JSONObject object = new JSONObject();
        //判断当前appName是否已注册
        try {
            AppInfo appInfo = appInfoService.getAppInfoByAppName(domain.getAppName());
            if (appInfo == null) {
                object.put("success", false);
                object.put("rspcod", "InvalidAppName");
                object.put("addSerial", "");
                object.put("msgGroup", "");
                return object;
            }
            if (!appInfo.getAppPassword().equals(domain.getAppPassword())) {//判断密码是否相同
                object.put("success", false);
                object.put("rspcod", "InvalidAppPassword");
                object.put("addSerial", "");
                object.put("msgGroup", "");
                return object;
            }
            domain.setAppId(appInfo.getId());
            //查询出回复已经超出失效时间的账号
            SmsAccount smsAccount = accountService.getInvalidBackAccountOutCall();
            if (smsAccount == null) {
                object.put("success", false);
                object.put("rspcod", "NoAccount");
                object.put("addSerial", "");
                object.put("msgGroup", "");
                return object;
            }
            String mobiles = domain.getMobiles();
            if (!StringUtils.isEmpty(mobiles)) {
                String[] mobilesArr = mobiles.split(",");
                if (mobilesArr.length > 500) {
                    object.put("success", false);
                    object.put("rspcod", "TooManyMobiles");
                    object.put("addSerial", "");
                    object.put("msgGroup", "");
                    return object;
                }
            } else {
                object.put("success", false);
                object.put("rspcod", "EmptyMobiles");
                object.put("addSerial", "");
                object.put("msgGroup", "");
                return object;
            }
            SmsInfo smsInfo = new SmsInfo();
            smsInfo.setReceiveUserPhone(domain.getMobiles());
            smsInfo.setMsgContent("【" + appInfo.getRemark() + "】" + domain.getSmsContent());
            object = httpSendSmsService.sendDSMS(smsInfo, smsAccount);
            if (object != null && object.getBoolean("success")) {
                accountService.updateUseTimeById(smsAccount.getId(), new Date());
            }
            if (object != null && object.getBoolean("success")) {
                domain.setSmsGroup(object.getString("msgGroup"));
            }
            object.put("addSerial", smsAccount.getAddSerial());
            domain.setCreateTime(new Date());
            domain.setAccountId(smsAccount.getId());
            publicUseService.saveAll(domain);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return object;
    }

    @RequestMapping(value = "/batchSmsSend", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "发送批量短信并保存相关信息", notes = "发送短信并保存相关信息接口")
    @ApiImplicitParam(name = "form", value = "SmsInfo实体", required = true, dataType = "SmsInfo")
    public JSONObject batchSmsSend(HttpServletRequest request, @RequestBody SmsDomain domain) {
        JSONObject object = new JSONObject();
        //判断当前appName是否已注册
        try {
            AppInfo appInfo = appInfoService.getAppInfoByAppName(domain.getAppName());
            if (appInfo == null) {
                List<String> a1 = new ArrayList();
                a1.add("InvalidAppName");
                object.put("rspcodArray", a1.toString());
                object.put("addSerial", "");
                object.put("msgGroup", "");
                return object;
            }
            if (!appInfo.getAppPassword().equals(domain.getAppPassword())) {//判断密码是否相同
                List<String> a1 = new ArrayList();
                a1.add("InvalidAppPassword");
                object.put("rspcodArray", a1.toString());
                object.put("addSerial", "");
                object.put("msgGroup", "");
                return object;
            }
            domain.setAppId(appInfo.getId());
            //查询出回复已经超出失效时间的账号
            SmsAccount smsAccount = accountService.getInvalidBackAccountOutCall();
            if (smsAccount == null) {
                List<String> a1 = new ArrayList();
                a1.add("NoAccount");
                object.put("rspcodArray", a1.toString());
                object.put("addSerial", "");
                object.put("msgGroup", "");
                return object;
            }
            SmsInfo smsInfo = new SmsInfo();
            String mobiles = domain.getMobiles();
            Integer groupNumber = domain.getGroupNumber();//分组数
            if (groupNumber == null) {
                groupNumber = 500;//分组数为空则按照500拆分手机号
            }
            if (!StringUtils.isEmpty(mobiles)) {
                List<List<String>> arrayList = new ArrayList<>();
                String[] mobilesArr = DStringUtil.removeNullStringArray(mobiles.split(","));
                if (mobilesArr.length > groupNumber) {
                    int num = groupNumber;
                    int count = mobilesArr.length % num == 0 ? mobilesArr.length / num : mobilesArr.length / num + 1;
                    for (int i = 0; i < count; i++) {
                        int index = i * num;
                        List<String> list = new ArrayList<>();
                        int j = 0;
                        while (j < num && index < mobilesArr.length) {
                            String mobile = mobilesArr[index++];
                            if (!StringUtils.isEmpty(mobile)) {
                                list.add(mobile);
                                j++;
                            }
                        }
                        arrayList.add(list);
                    }
                } else {
                    arrayList.add(Arrays.asList(mobilesArr));
                }
                List<String> groupArray = new ArrayList<>();
                List<String> rspcodArray = new ArrayList();
                for (List<String> list : arrayList) {
                    smsInfo.setReceiveUserPhone(StringUtil.join(list.toArray(), ","));
                    smsInfo.setMsgContent("【" + appInfo.getRemark() + "】" + domain.getSmsContent());
                    JSONObject obj = httpSendSmsService.sendDSMS(smsInfo, smsAccount);
                    Thread.currentThread().sleep(2000);
                    System.out.println("====" + new Date());
                    groupArray.add(obj.getString("msgGroup"));
                    rspcodArray.add(obj.getString("rspcod"));
                }
                if (groupArray.size() > 0) {
                    accountService.updateUseTimeById(smsAccount.getId(), new Date());
                }
                if (groupArray.size() > 0) {
                    domain.setSmsGroup(groupArray.toString());
                }
                object.put("addSerial", smsAccount.getAddSerial());
                object.put("msgGroupArr", groupArray.toString());//分批次msgGroup
                object.put("mobilesArr", arrayList.toString());//分批次手机号
                object.put("rspcodArray", rspcodArray.toString());//每一批次响应结果
                domain.setCreateTime(new Date());
                domain.setAccountId(smsAccount.getId());
                domain.setMobiles(arrayList.toString());
                publicUseService.saveAll(domain);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return object;
    }

    @RequestMapping(value = "/addBackInfo", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "获取回执信息", notes = "发送短信获取回执信息")
    public BusinessMessage getBackInfo(@RequestBody SmsBackInfo smsBackInfo) {
        smsBackInfo.setCreateTime(new Date());
        System.out.println("保存回执信息:" + smsBackInfo);
        BusinessMessage message = smsBackInfoService.saveBackInfo(smsBackInfo);
        return message;
    }

    @RequestMapping(value = "/addLastInfo", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "保存上行信息", notes = "发送短信获取上行信息")
    public BusinessMessage getLastInfo(@RequestBody SmsMoInfo moInfo) {
        System.out.println("获取上行信息:" + moInfo.toString());
        String smsInfoId = infoService.getSmsInfoIdByMobile(moInfo.getAddSerial());
        moInfo.setSmsInfoId(smsInfoId);
        BusinessMessage message = moInfoService.saveLastInfo(moInfo);
        return message;
    }
}
